﻿using LogAnalyzer.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace LogAnalyzer.ViewModel
{
    public class RouteGridViewModel
    {
        public List<RoutingData> data { get; set; }

        public event EventHandler RowClick;

        public void OnRowClick(int rowClicked)
        {
            if (RowClick != null)
            {
                if (rowClicked >= 0 && rowClicked < data.Count)
                {
                    RowClick(data[rowClicked], new EventArgs());
                }
            }
        }

        public string info { get; set; }

        public RouteGridViewModel()
        {
            data = new List<RoutingData>();
            foreach (var l in App.Log)
            {
                if (l.what.type == Util.MessageType.Route && l.what.content.routeCount == "0")
                {
                    var route = new RoutingData();
                    route.RequestingNode = l.to.nodeId;
                    route.RequestedNode = l.what.content.key;
                    route.RouteId = l.what.content.id;

                    var endingMsg = App.Log.FirstOrDefault(x => x.what.type == Util.MessageType.RouteResponse && x.what.content.id == route.RouteId);
                    route.EndingNode = Util.Proc(l.what.content.key) ?? endingMsg.what.content.node.nodeId;

                    data.Add(route);
                }
            }

            decimal totalRoutings = data.Count();
            decimal totalGood = data.Count(x => x.SuccessfulRouting);
            decimal totalBad = data.Count(x => !x.SuccessfulRouting);
            decimal percent = ((totalGood/totalRoutings) * 100);

            info = string.Format("Total Routings: {0} | Successful Routings: {1} | Unsuccessful Routings: {2} | Success Percentage: {3}%", totalRoutings, totalGood, totalBad, Math.Ceiling(percent));
        }
    }
}
